﻿var databasetypelist = GetDbDataType();
var ServiceId = GetQueryString("Id");
var dataSourceId = GetQueryString("dataSourceId");
$("#ServiceId").val(ServiceId);
$("#SourceId").val(dataSourceId);
var sysno = GetQueryString("sysno");
$(function () {

    $("#RelationTable").attr("href", ($("#RelationTable").attr("href") + "?Id=" + ServiceId + "&dataSourceId=" + dataSourceId));
    $("#CreateTable").attr("href", $("#CreateTable").attr("href") + "?Id=" + ServiceId + "&dataSourceId=" + dataSourceId);
    getServiceDetails();
    getDataSourceDetails();
    $("#Create-Form").validate({
        submitHandler: function () {
            var columnstr = "";
            var columns = $("#table-column-details tbody tr[disabled-data=false]");
            var logocolumns = $(".LogoColumn:checked");
            var logocolumnstr = "";
            if (columns.length > 0) {
                for (var i = 0; i < columns.length; i++) {
                    var tempjson = JSON.parse($(columns[i]).attr("data"));
                    columnstr += tempjson.Id + "," + $("#dtcol-name-" + tempjson.editNum).val() + "," + JSON.parse($("#dtcol-type-" + tempjson.editNum).val()).Name + "," + $("#dtcol-length-" + tempjson.editNum).val() + ",";
                    columnstr += $("#dtcol-null-" + tempjson.editNum).is(':checked') ? "true" : "false";
                    if (i != columns.length - 1)
                        columnstr += ",";
                }
                for (var j = 0; j < logocolumns.length; j++) {
                    var tempobj = $(logocolumns[j]);
                    logocolumnstr += tempobj.val();
                    if (j < (logocolumns.length - 1)) {
                        logocolumnstr += ",";
                    }
                }
                console.log(logocolumnstr);
                console.log(columnstr);
                $("#DataIdentity").val(logocolumnstr);
                $("#ColumnMapping").val(columnstr);
                $("#IsRawDataTable").val($("#IsRawDataTable_check").is(':checked') ? "true" : "false");
                var url = "DataServiceManagement.html";
                $.ajax({
                    url: apiUrl,
                    type: "Post",
                    dataType: "json",
                    data: $("#Create-Form").serialize(),
                    success: function (data) {
                        if (data.IsSccuess) {
                            ShowGritter("保存成功", 2, url);
                        } else {
                            if (IsLogined(data.ErrorCode)) {
                                alert("失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                            }
                        }
                    },
                    beforeSend: function () {
                        ShowGritter("提交中");
                    }
                });
            } else {
                alert("暂无可提交的列，请修改数据源后在关联数据表！");
            }
        }
    });
});
var dtcoltypeChange = function (obj) {
    var $this = $(obj);
    var tempjson = JSON.parse($this.val());
    if (tempjson.NeedLength) {
        $this.parent().next().children().removeAttr("disabled");
    } else {
        $this.parent().next().children().val("0");
        $this.parent().next().children().attr("disabled", "disabled");
    }
}
//获取服务的详细信息
var getServiceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": sysno,
            "sys:act": "GetDataService",
            "ServiceId": ServiceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                $("#ServiceName").val(data.Data.Name);
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
var getDataSourceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "ETL",
            "sys:act": "GetDataSource",
            "DataServiceId": ServiceId,
            "DataSourceId": dataSourceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                $("#DataSourceName").val(data.Data.Name);//名称
                ProductionTable(data.Data.Columns);
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert("失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}

var ProductionTable = function (data) {
    if (databasetypelist.length <= 0) {
        alert("暂无可用数据库类型");
    } else {
        var trlist = "";
        var logotrlist = "";
        for (var i = 0; i < data.length; i++) {
            var $this = data[i];
            var str = $this.Name.split(':');
            if (str.length != 2) {
                trlist += AssembleData({ name: $this.Name, colum: "", type: $this.Type, editNum: i, Id: $this.Id });
            } else {
                trlist += AssembleData({ name: str[0], colum: str[1], type: $this.Type, editNum: i, Id: $this.Id });
            }
            logotrlist += (AssembleLogoData({ name: str[0], colum: (str[1] == undefined ? "" : str[1]), type: $this.Type, editNum: i, Id: $this.Id }));
        }
        $("#table-column-details").append(trlist);
        $("#table-logo-details").append(logotrlist);
    }

}
//传入data对象返回一行的表格数据
var AssembleData = function (data) {
    var tr = ("<tr data='" + JSON.stringify(data) + "' class='row_" + data.editNum + "'disabled-data='false' ><td>");
    if (data.colum == "") {
        tr += (data.name + "</td>");
    } else {
        tr += (data.name + ":" + data.colum + "</td>");
    }
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td><input type=\"text\" class='field' value=\"" + (data.colum == "" ? data.name : data.colum) + "\" id=\"dtcol-name-" + data.editNum + "\"/></td>");
    tr += ("<td><select id=\"dtcol-type-" + data.editNum + "\" onchange=\"dtcoltypeChange(this)\" >");
    for (var i = 0; i < databasetypelist.length; i++) {
        tr += ("<option  value='" + JSON.stringify(databasetypelist[i]) + "'>" + databasetypelist[i].Name + "</option>");
    }
    tr += ("</select></td>");
    tr += ("<td><input type=\"text\" value=\"50\"  id=\"dtcol-length-" + data.editNum + "\"  /></td>");
    tr += ("<td><input type=\"checkbox\" value=\"true\"  id=\"dtcol-null-" + data.editNum + "\" /></td><td><a href='javascript:void(0);' onclick='deleteRow(this)'><i class=\"fa  fa-times-circle\"></i></a></td></tr>");
    return tr;
}
//传入data对象返回一行的表格数据
var AssembleLogoData = function (data) {
    var tr = ("<tr class='row_" + data.editNum + "'>");
    tr += ("<td><label class=\"checkbox\"><input type=\"checkbox\" class=\"LogoColumn\" value=\"" + data.Id + "\" /> <i></i></label></td>");
    if (data.colum == "" || data.colum == undefined) {
        tr += ("<td>" + data.name + "</td></tr>");
    } else {
        tr += ("<td>" + data.name + ":" + data.colum + "</td></tr>");
    }

    return tr;
}
//删除当前行和标识列
var deleteRow = function (obj) {
    if (confirm("是否删除当前列和标识列？")) {
        var $this = $(obj).parent().parent();
        $("#table-logo-details ." + $this.attr("class")).find(".LogoColumn").attr("disabled", "disabled");
        $("#table-logo-details ." + $this.attr("class")).find(".LogoColumn").removeAttr("checked");
        $("#table-logo-details ." + $this.attr("class")).attr("disabled-data", "true");
        $this.attr("disabled-data", "true");
        $this.find("input").attr("disabled", "disabled");
        $this.find("select").attr("disabled", "disabled");
        $this.find("a").attr("onclick", "EnableRow(this)");;
        $this.find("a").html("<i class='fa fa-share-square'></i>");
    }
}
//删除当前行和标识列
var EnableRow = function (obj) {
    if (confirm("是否恢复当前列和标识列？")) {
        var $this = $(obj).parent().parent();
        $("#table-logo-details ." + $this.attr("class")).find(".LogoColumn").removeAttr("disabled");
        $("#table-logo-details ." + $this.attr("class")).attr("disabled-data", "false");
        $this.removeAttr("disabled-data");
        $this.find("input").removeAttr("disabled");
        $this.find("select").removeAttr("disabled");
        $this.find("a").attr("onclick", "deleteRow(this)");;
        $this.find("a").html("<i class=\"fa  fa-times-circle\"></i>");
    }
}